typedef struct ListNode ListNode;

struct ListNode *detectCycle(struct ListNode *head) {
    ListNode* slow = head;
    ListNode* fast = head;

    while(fast && (fast->next))
    {
        fast = fast->next->next;
        slow = slow->next;
        if(fast == slow)
        {
            ListNode* meet = slow;
            while(meet != head)
            {
                meet = meet->next;
                head = head->next;
            }
            return meet;
        }
    }
    return NULL;
}

//cpp
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* cur = head;
        set<ListNode*> s;
        while(cur)
        {
            if(s.count(cur))
                return cur;
            
            s.insert(cur);
            cur = cur->next;
        }

        return nullptr;
    }
};